//
//  WBHomeViewController.swift
//  WB123
//
//  Created by xuyunde mac pro on 2017/6/29.
//  Copyright © 2017年 NSObjiect. All rights reserved.
//

import UIKit
import YYModel
// cell可重用标识符
private let homeCeLLID = "homeCeLLID"
class WBHomeViewController: WBBaseViewController {
    
    // 创建全局的viewModel
    fileprivate lazy var homeViewModel: WBHomeViewModel = WBHomeViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        // 如果用户没有登录 设置信息
        if !isLogin {
            visitorView?.setupVisitorViewInfo(imgName: nil, title: nil)
            return
        }

        setupUI()
        
        loadData()
    }
    // 设置tabelView信息
    private func setupTableViewInfo(){
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(WBHomeCell.self, forCellReuseIdentifier: homeCeLLID)
        // 设置行高---自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        // --预估行高
        tableView.estimatedRowHeight = 300
        // 设置分割线样式
        tableView.separatorStyle = .none
        //设置footView
        tableView.tableFooterView = footerView
        // 添加系统刷新控件
        tableView.addSubview(refreshControl)
    }
    
    // 设置视图
    private func setupUI(){
        navigationController?.view.insertSubview(pulldownTipLabel, belowSubview: navigationController!.navigationBar)
        
        setupNav()
        setupTableViewInfo()
    }
    // 点击左侧按钮方法
    
    
    // 设置导航WBTempViewController
    private func setupNav(){
        // 左边按钮
    navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", title: nil, target: self, action: #selector(leftButtonClick))
        // 右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", title: nil, target: self, action: #selector(rightButtonClick))
    }
    //MARK: - 懒加载控件
    // 自定义上拉刷新
    fileprivate lazy var footerView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        //颜色
        view.color = ThemeColor
        return view
    }()
    
    // 系统的下拉刷新控件
    fileprivate lazy var refreshControl: LRefreshControl = {
        let view = LRefreshControl()
        // 监听事件
        view.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
        return view
    }()
    // 刷新微博指示器
    fileprivate lazy var pulldownTipLabel: UILabel = {
        let lab = UILabel(frame: CGRect(x: 0, y: 64 - 30, width: SCREENW, height: 30))
        lab.backgroundColor = ThemeColor
        lab.font = UIFont.systemFont(ofSize: NormalFontSize)
        lab.textColor = UIColor.white
        lab.textAlignment = .center
        lab.isHidden = true
        return lab
    }()

}

extension WBHomeViewController{
    func loadData(){
        
        homeViewModel.getHomeData(isPullUp: self.footerView.isAnimating) { (isFinish,count) in
            
//            self.endRefreshing()
            // 判断
            if !isFinish{
                print("请求失败----*")
                return
            }else{
                // 判断是否是首次请求数据 或者是下拉刷新
                if !self.footerView.isAnimating{
                    self.setupPulldownTipLabelAnim(count: count)
                }
                self.tableView.reloadData()
            }
            self.endRefreshing()
        }
        
    }
    // 设置pulldownTipLabel的动画
    // 只有第一次和下拉刷新中设置动画
    fileprivate func setupPulldownTipLabelAnim(count: Int){
        
        // 判断是否显示
        if !self.pulldownTipLabel.isHidden {
            return
        }
        
        self.pulldownTipLabel.isHidden = false
        
        // 记录描述文字
        let text: String
        if count > 0 {
            text = "您更新了\(count)条微博"
        }else{
            text = "您已经是最新的微博数据拉"
        }
        // 赋值
        pulldownTipLabel.text = text
        
        // 设置动画
        UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
            self.pulldownTipLabel.transform = CGAffineTransform(translationX: 0, y: 30)
        }) { (_) in
            UIView.animate(withDuration: 1, animations: {
                self.pulldownTipLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                // 隐藏
                self.pulldownTipLabel.isHidden = true
            })
        }
    }

    
    // 监听下拉刷新开始请求数据
    @objc fileprivate func refreshAction(){
        print("刷新数据")
        loadData()
    }
    
    fileprivate func endRefreshing(){
        
        self.footerView.stopAnimating()
        self.refreshControl.endRefreshing()
    }
}

extension WBHomeViewController: UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.dataList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "homeCeLLID", for: indexPath) as! WBHomeCell
        //赋值
        cell.statusViewModel = homeViewModel.dataList[indexPath.row]
        // cell 的选中效果
        cell.selectionStyle = .none
//        let homeModel = dataList[indexPath.row]
//        cell.homeModel = homeModel
        return cell
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 如果到最后一行,就应该footView动画
        // footerView.isAnimating是否在执行动画
        if indexPath.row == homeViewModel.dataList.count - 1 && !self.footerView.isAnimating{
            print(indexPath.row,"行号")
            //执行动画
            self.footerView.startAnimating()
            //发送网络请求
            loadData()
        }
    }
}


//监听按钮
extension WBHomeViewController{
    @objc fileprivate func leftButtonClick(){
        print("点左侧")
    }
    @objc fileprivate func rightButtonClick(){
        print("点右侧")
        let tempVC = WBTempViewController()
        // 隐藏tabbar----------
        //        tempVC.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(tempVC, animated: true)
    }
}
